/** @file @Wgraph.java
 *
 *  @author Jon Turner
 *  @date 2011
 *  This is open source software licensed under the Apache 2.0 license.
 *  See http://www.apache.org/licenses/LICENSE-2.0 for details.
 */

package algoLib.dataStructures.graphs;
import algoLib.dataStructures.basic.*;

/** Data structure for undirected graph with edge weights.
 *  Adds edge weights to Graph class.
 */
public class Wgraph extends Graph {
	int[]	wt;			///< array of edge weights

	/** Construct Graph with space for a specified # of vertices and edges.
	 *  @param N1 is number of vertices in the graph
	 *  @param maxEdge1 is the maximum number of edges
	 */
	public Wgraph(int N, int maxEdge) {
		super(N,maxEdge);
		wt = new int[maxEdge+1];
		for (int e = 0; e <= maxEdge; e++) wt[e] = 0;
	}

	/** Get the weight of an edge.
	 *  @param e is the edge of interest
	 *  @return the weight of e, or 0 if e is not a valid edge.
	 */
	public int weight(int e) {
		assert(0 <= e && e <= maxEdge);
		return (left(e) == 0 ? 0 : wt[e]);
	}
	
	/** Set the weight of an edge.
	 *  @param e is the edge of interest
	 *  @param wt is the desired weight
	 */
	public void setWeight(int e, int w) {
		assert(0 <= e && e <= maxEdge);
		wt[e] = w;
	}
	
	/** Construct a String representation of the Wgraph object.
	 *  For small graphs (at most 26 vertices), vertices are
	 *  represented in the String as lower case letters.
	 *  For larger graphs, vertices are represented by integers.
	 *  @param s is a String object provided by the caller which
	 *  is modified to provide a representation of the Graph.
	 *  @return a reference to the String
	 */
	public String toString() {
		String s = "";
		for (int u = 1; u <= n(); u++) {
			if (firstAt(u) == 0) continue;
			for (int e = firstAt(u); e != 0; e = nextAt(u,e)) {
				s += "(";
				if (n() <= 26)
					s += ((char) ('a'+(u-1))) + ","
					     + ((char) ('a'+(mate(u,e)-1)))
					     + "," + weight(e);
				else 
					s += u + "," + mate(u,e) + ","
					     + weight(e);
				s += ")"; if (nextAt(u,e) != 0) s += " ";
			}
			s += "\n";
		}
		return s;
	}
}
